//
//  KLNewSendKeyVC.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 17/3/10.
//  Copyright © 2017年 陈宾鹏. All rights reserved.
//

#import "KLNewSendKeyVC.h"
#import "KLHelp.h"
#import "KLHttpAPI.h"
#import "HemaConst.h"
#import "JRToast.h"
#import "Masonry.h"
#import "BuleFuction.h"
#import <AddressBookUI/ABPeoplePickerNavigationController.h>
#import <AddressBook/ABPerson.h>
#import <AddressBookUI/ABPersonViewController.h>
#import "WSDatePickerView.h"
#import "NSData+hex.h"
#import "BeeCloud+Utils.h"
#import "UIAlertView+Blocks.h"
#import "HemaFunction.h"
#import "KLRechargeViewController.h"

@interface KLNewSendKeyVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,ABPeoplePickerNavigationControllerDelegate,BeeCloudDelegate,UIActionSheetDelegate,UIScrollViewDelegate>
{
    NSString *power;
    NSString *updatetime;
}
@property(nonatomic,strong)NSString *money;
@property(nonatomic,strong)NSString *totalFee;
@property(nonatomic,strong)NSString *trade_no;

@property(nonatomic,strong) UITableView *showTable;
@property(nonatomic,strong) UIView *headView;
@property(nonatomic,strong) UITextField *mobileField;
@property(nonatomic,strong) UIButton *mobileListBtn;

@property(nonatomic,strong) UIButton *beginTime;
@property(nonatomic,strong) UIButton *endTime;
@property(nonatomic,strong) UIButton *foreverBrunch;
@property(nonatomic,strong) UIButton *selectGroup2;
@property(nonatomic,strong) UIButton *selectGroup3;
@property(nonatomic,strong) UIButton *notOnLine;
@property(nonatomic,strong) UILabel *footerLabel;

@property(nonatomic,strong) UIButton *sendBrunch;

@property(nonatomic,strong) NSString *beginTimeToLock;
@property(nonatomic,strong) NSString *endTimeToLock;
@end

@implementation KLNewSendKeyVC

-(UITableView *)showTable{
    if(!_showTable){
        _showTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, UI_View_Height-20) style:UITableViewStyleGrouped];
        _showTable.backgroundColor = [UIColor whiteColor];
        _showTable.delegate = self;
        _showTable.dataSource = self;
        _showTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _showTable.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 90)];
        _showTable.tableFooterView.backgroundColor = [UIColor whiteColor];
        [_showTable.tableFooterView addSubview:self.footerLabel];
        [_showTable.tableFooterView addSubview:self.sendBrunch];
        [self.sendBrunch mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(10);
            make.right.mas_equalTo(-10);
            make.bottom.mas_equalTo(-10);
            make.height.mas_equalTo(40);
        }];
    }
    return _showTable;
}

-(UIButton *)beginTime{
    if(!_beginTime){
        _beginTime = [[UIButton alloc]initWithFrame:CGRectMake(10, 10, (UI_View_Width-30)/2, 40)];
        [_beginTime setTitle:@"钥匙的起始时间" forState:UIControlStateNormal];
        _beginTime.titleLabel.font = [UIFont systemFontOfSize:17 weight:0.5];
        [_beginTime setTitleColor:RGB_UI_COLOR(8, 128, 181) forState:UIControlStateNormal];
        _beginTime.layer.masksToBounds = YES;
        _beginTime.layer.cornerRadius = 5;
        _beginTime.layer.borderWidth = 2;
        _beginTime.layer.borderColor = RGB_UI_COLOR(8, 128, 181).CGColor;
        [_beginTime addTarget:self action:@selector(selectBeginTime:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _beginTime;
}

-(UIButton *)endTime{
    if(!_endTime){
        _endTime = [[UIButton alloc]initWithFrame:CGRectMake(10+(UI_View_Width-30)/2+10, 10, (UI_View_Width-30)/2, 40)];
        [_endTime setTitle:@"钥匙的结束时间" forState:UIControlStateNormal];
        _endTime.titleLabel.font = [UIFont systemFontOfSize:17 weight:0.5];
        [_endTime setTitleColor:RGB_UI_COLOR(8, 128, 181) forState:UIControlStateNormal];
        _endTime.layer.masksToBounds = YES;
        _endTime.layer.cornerRadius = 5;
        _endTime.layer.borderWidth = 2;
        _endTime.layer.borderColor = RGB_UI_COLOR(8, 128, 181).CGColor;
        [_endTime addTarget:self action:@selector(selectEndTime:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _endTime;
}

-(UIButton *)foreverBrunch{
    if(!_foreverBrunch){
        _foreverBrunch = [[UIButton alloc]init];
        [_foreverBrunch setImage:[UIImage imageNamed:@"未选"] forState:UIControlStateNormal];
        [_foreverBrunch setSelected:NO];
        [_foreverBrunch addTarget:self action:@selector(foreverBrunch:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _foreverBrunch;
}

-(UIButton *)selectGroup2{
    if(!_selectGroup2){
        _selectGroup2 = [[UIButton alloc]init];
        [_selectGroup2 setImage:[UIImage imageNamed:@"deSelectGroup"] forState:UIControlStateNormal];
        [_selectGroup2 setSelected:NO];
        [_selectGroup2 addTarget:self action:@selector(selectGroup2:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _selectGroup2;
}

-(UIButton *)selectGroup3{
    if(!_selectGroup3){
        _selectGroup3 = [[UIButton alloc]init];
        [_selectGroup3 setImage:[UIImage imageNamed:@"deSelectGroup"] forState:UIControlStateNormal];
        [_selectGroup3 setSelected:NO];
        [_selectGroup3 addTarget:self action:@selector(selectGroup3:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _selectGroup3;
}

-(UIButton *)notOnLine{
    if(!_notOnLine){
        _notOnLine = [[UIButton alloc]initWithFrame:CGRectMake(5, 10, UI_View_Width-10, 40)];
        [_notOnLine setBackgroundImage:[UIImage imageNamed:@"notOnLine"] forState:UIControlStateNormal];
        [_notOnLine setTitle:@"同步开锁" forState:UIControlStateNormal];
        _notOnLine.titleLabel.font = [UIFont systemFontOfSize:16];
        _notOnLine.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _notOnLine.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
        [_notOnLine setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_notOnLine addTarget:self action:@selector(notOnLine:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _notOnLine;
}

-(UILabel *)footerLabel{
    if(!_footerLabel){
        _footerLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, UI_View_Width-20, 30)];
        _footerLabel.textColor = [UIColor redColor];
        _footerLabel.font = [UIFont systemFontOfSize:14];
        _footerLabel.text = @"请慎重选择，该钥匙将不被平台监管";
        _footerLabel.hidden = YES;
    }
    return _footerLabel;
}

-(UIButton *)sendBrunch{
    if(!_sendBrunch){
        _sendBrunch = [[UIButton alloc]init];
        [_sendBrunch setTitle:@"发送" forState:UIControlStateNormal];
        _sendBrunch.titleLabel.font = [UIFont systemFontOfSize:19 weight:0.6];
        _sendBrunch.layer.masksToBounds = YES;
        _sendBrunch.layer.cornerRadius = 5.f;
        _sendBrunch.backgroundColor = [KLHelp mainBlueColor];
        [_sendBrunch addTarget:self action:@selector(sendBrunchKeys:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendBrunch;
}
//============================================================================================================
- (void)viewDidLoad {
    [super viewDidLoad];
    //updatetime默认为0，即同步开锁
    updatetime = @"0";
    power = nil;//默认为空，用户必须选择
    self.navigationItem.title = @"分发钥匙";
    [self.view addSubview:self.showTable];
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    }];
    //UITableView的头视图
    self.headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 70)];
    self.headView.backgroundColor = [UIColor whiteColor];
    self.showTable.tableHeaderView = self.headView;
    //输入手机号
    self.mobileField = [[UITextField alloc]init];
    self.mobileField.placeholder = @"请输入对方手机号";
    self.mobileField.borderStyle = UITextBorderStyleRoundedRect;
    self.mobileField.keyboardType = UIKeyboardTypeNumberPad;
    self.mobileField.delegate = self;
    [self.headView addSubview:self.mobileField];
    [self.mobileField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.top.mas_equalTo(20);
        make.height.mas_equalTo(30);
        make.right.mas_equalTo(-70);
    }];
    //点击进入通讯录按钮
    self.mobileListBtn = [[UIButton alloc]init];
    [self.mobileListBtn setBackgroundImage:[UIImage imageNamed:@"通讯录"] forState:UIControlStateNormal];
    [self.mobileListBtn addTarget:self action:@selector(selectMobileList:) forControlEvents:UIControlEventTouchUpInside];
    [self.headView addSubview:self.mobileListBtn];
    [self.mobileListBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(20);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(30);
    }];
    //获取钥匙详情
    NSLog(@"该锁的详细信息:%@",self.lockDetailDic);
}-(void)doBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return 2;
            break;
        case 2:
            return 1;
            break;
        default:
            return 0;
            break;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sendBrunch"];
    if(!cell){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"sendBrunch"];
    }else{
        //删除cell的所有子视图
        while ([cell.contentView.subviews lastObject] != nil){
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if(indexPath.section == 0){
        //创建起始/结束按钮
        [cell.contentView addSubview:self.beginTime];
        [cell.contentView addSubview:self.endTime];
        //创建显示文字
        UILabel *label = [[UILabel alloc]init];
        label.text = @"永久钥匙";
        label.font = [UIFont systemFontOfSize:16];
        [cell.contentView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(35);
            make.top.equalTo(self.beginTime.mas_bottom).with.offset(15);;
        }];
        //创建勾选按钮
        [cell.contentView addSubview:self.foreverBrunch];
        [self.foreverBrunch mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(10);
            make.width.and.height.mas_equalTo(20);
            make.top.equalTo(self.beginTime.mas_bottom).with.offset(15);
        }];
    }else if (indexPath.section == 1){
        UILabel *label = [[UILabel alloc]init];
        label.font = [UIFont systemFontOfSize:16];
        [cell.contentView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(35);
            make.centerY.equalTo(cell.contentView);
        }];
        NSString *style = [self.lockDetailDic objectForKey:@"type"];
        switch (indexPath.row) {
            case 0:{
                if(style.integerValue == 3){
                    cell.userInteractionEnabled = NO;
                    cell.backgroundColor = RGB_UI_COLOR(242, 242, 242);
                }
                label.text = @"临时钥匙(可分发)";
                [cell.contentView addSubview:self.selectGroup2];
                [self.selectGroup2 mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.mas_equalTo(10);
                    make.width.and.height.mas_equalTo(20);
                    make.centerY.equalTo(cell.contentView);
                }];
                break;
            }
            case 1:{
                if(style.integerValue == 3){
                    cell.userInteractionEnabled = NO;
                    cell.backgroundColor = RGB_UI_COLOR(242, 242, 242);
                }
                label.text = @"临时钥匙(不可分发)";
                [cell.contentView addSubview:self.selectGroup3];
                [self.selectGroup3 mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.mas_equalTo(10);
                    make.width.and.height.mas_equalTo(20);
                    make.centerY.equalTo(cell.contentView);
                }];
                break;
            }
            default:
                break;
        }
    }else if (indexPath.section == 2){
        [cell.contentView addSubview:self.notOnLine];
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
            return 100;
            break;
        case 1:
            return 40;
            break;
        case 2:
            return 50;
            break;
        default:
            return 0;
            break;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *sectionView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 34)];
    sectionView.backgroundColor = RGB_UI_COLOR(234, 234, 234);
    UIImageView *noticeImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"nitice_front_bar.jpg"]];
    [sectionView addSubview:noticeImage];
    [noticeImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.top.mas_equalTo(5);
        make.bottom.mas_equalTo(-5);
        make.width.mas_equalTo(5);
    }];
    UILabel *noticeText = [[UILabel alloc]initWithFrame:CGRectMake(25, 2, 200, 30)];
    noticeText.font = [UIFont systemFontOfSize:17 weight:0.7];
    switch (section) {
        case 0:
            noticeText.text = @"钥匙有效期";
            break;
        case 1:
            noticeText.text = @"钥匙类型";
            break;
        case 2:
            noticeText.text = @"最长离线开锁时间";
            break;
        default:
            break;
    }
    [sectionView addSubview:noticeText];
    return sectionView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 34.f;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *vw = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 1)];
    vw.backgroundColor = [UIColor whiteColor];
    return vw;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1f;
}

#pragma mark - 勾选按钮执行方法
-(void)selectBeginTime:(UIButton *)sender{
    //选择起始日期
    NSLog(@"选择起始日期");
    WSDatePickerView *datepicker = [[WSDatePickerView alloc] initWithCompleteBlock:^(NSDate *startDate) {
        NSString *date = [startDate stringWithFormat:@"yyyy-MM-dd HH:mm"];
        NSLog(@"时间： %@",date);
        [sender setTitle:date forState:UIControlStateNormal];
        self.beginTimeToLock = [startDate stringWithFormat:@"yyMMddHHmmss"];
    }];
    if(self.endTimeToLock != nil){
        NSDateFormatter *ft = [[NSDateFormatter alloc]init];
        [ft setDateFormat:@"yyyy-MM-dd HH:mm"];
        datepicker.maxLimitDate = [ft dateFromString:self.endTime.titleLabel.text];
    }
    datepicker.minLimitDate = [NSDate date];
    
    datepicker.datePickerStyle = DateStyleShowYearMonthDayHourMinute;
    [datepicker show];
    
}

-(void)selectEndTime:(UIButton *)sender{
    //选择结束日期
    NSLog(@"选择结束日期");
    WSDatePickerView *datepicker = [[WSDatePickerView alloc] initWithCompleteBlock:^(NSDate *startDate) {
        NSString *date = [startDate stringWithFormat:@"yyyy-MM-dd HH:mm"];
        NSLog(@"时间： %@",date);
        [sender setTitle:date forState:UIControlStateNormal];
        self.endTimeToLock = [startDate stringWithFormat:@"yyMMddHHmmss"];
    }];
    if(self.beginTimeToLock != nil){
        NSDateFormatter *ft = [[NSDateFormatter alloc]init];
        [ft setDateFormat:@"yyyy-MM-dd HH:mm"];
        datepicker.minLimitDate = [ft dateFromString:self.beginTime.titleLabel.text];
    }else{
        datepicker.minLimitDate = [NSDate date];
    }
    datepicker.datePickerStyle = DateStyleShowYearMonthDayHourMinute;
    [datepicker show];
    
}

-(void)foreverBrunch:(UIButton *)sender{
    //选择永久钥匙
    NSLog(@"选择永久钥匙");
    [sender setSelected:!sender.isSelected];
    if(sender.isSelected){
        [sender setImage:[UIImage imageNamed:@"选中"] forState:UIControlStateNormal];
        self.beginTime.enabled = NO;
        self.beginTime.alpha = 0.4;
        self.endTime.enabled = NO;
        self.endTime.alpha = 0.4;
    }else{
        [sender setImage:[UIImage imageNamed:@"未选"] forState:UIControlStateNormal];
        self.beginTime.enabled = YES;
        self.beginTime.alpha = 1;
        self.endTime.enabled = YES;
        self.endTime.alpha = 1;
    }
}

-(void)selectGroup2:(UIButton *)sender{
    //选择临时钥匙（可分发）
    NSLog(@"选择临时钥匙（可分发）");
    [sender setSelected:!sender.isSelected];
    if(sender.isSelected){
        [sender setImage:[UIImage imageNamed:@"selectGroup"] forState:UIControlStateNormal];
        [self.selectGroup3 setSelected:YES];
        [self selectGroup3:self.selectGroup3];
        power = @"01";
    }else{
        [sender setImage:[UIImage imageNamed:@"deSelectGroup"] forState:UIControlStateNormal];
    }
}

-(void)selectGroup3:(UIButton *)sender{
    //选择临时钥匙（不可分发）
    NSLog(@"选择临时钥匙（不可分发）");
    [sender setSelected:!sender.isSelected];
    if(sender.isSelected){
        [sender setImage:[UIImage imageNamed:@"selectGroup"] forState:UIControlStateNormal];
        [self.selectGroup2 setSelected:YES];
        [self selectGroup2:self.selectGroup2];
        power = @"00";
    }else{
        [sender setImage:[UIImage imageNamed:@"deSelectGroup"] forState:UIControlStateNormal];
    }
}

-(void)notOnLine:(UIButton *)sender{
    //选择最长离线开锁时间
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:@"同步开锁" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.notOnLine setTitle:@"同步开锁" forState:UIControlStateNormal];
        self.footerLabel.hidden = YES;
        updatetime = @"0";
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"1小时" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.notOnLine setTitle:@"1小时" forState:UIControlStateNormal];
        self.footerLabel.hidden = YES;
        updatetime = @"1";
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"12小时" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.notOnLine setTitle:@"12小时" forState:UIControlStateNormal];
        self.footerLabel.hidden = YES;
        updatetime = @"12";
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"24小时" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.notOnLine setTitle:@"24小时" forState:UIControlStateNormal];
        self.footerLabel.hidden = YES;
        updatetime = @"24";
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"7天" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.notOnLine setTitle:@"7天" forState:UIControlStateNormal];
        self.footerLabel.hidden = YES;
        updatetime = @"148";
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"30天" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.notOnLine setTitle:@"30天" forState:UIControlStateNormal];
        self.footerLabel.hidden = YES;
        updatetime = @"720";
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"无需同步" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.notOnLine setTitle:@"无需同步" forState:UIControlStateNormal];
        self.footerLabel.hidden = NO;
        updatetime = @"10000";
    }]];
    [self presentViewController:alertController animated:true completion:nil];
}

-(void)sendBrunchKeys:(UIButton *)sender{
    //如果用户没有选择钥匙类型，直接返回
    if(power == nil){
        [JRToast showWithText:@"请选择要发出的钥匙类型"];
        return ;
    }
    if(![HemaFunction xfunc_isMobileNumber:self.mobileField.text]){
        [KLHelp showTextHUDforView:self.view text:@"请输入正确的手机号"];
        return;
    }
    //钥匙的有效期
    NSString *startDate; NSString *endDate;
    if(self.foreverBrunch.isSelected){
        startDate = @"0";
        endDate = @"0";
    }else{
        if(![self.beginTime.titleLabel.text hasPrefix:@"2"] || ![self.endTime.titleLabel.text hasPrefix:@"2"]){
            [JRToast showWithText:@"请选择钥匙有效期"];
            return ;
        }else{
            startDate = [NSString stringWithFormat:@"%@:00",self.beginTime.titleLabel.text];
            endDate = [NSString stringWithFormat:@"%@:00",self.endTime.titleLabel.text];
        }
    }
    NSString *style = [self.lockDetailDic objectForKey:@"type"];
    //先获取钥匙的价格
    [self getGroupTotalFeeWithStartDate:startDate endDate:endDate style:style];
    
}

-(void)selectMobileList:(UIButton *)sender{
    //调取通讯录
    [KLHelp showHUDAddedTo:self.view animated:YES];
    ABPeoplePickerNavigationController *nav = [[ABPeoplePickerNavigationController alloc] init];
    nav.peoplePickerDelegate = self;
    
    //这个变量用于记录授权是否成功，即用户是否允许我们访问通讯录
    int __block tip=0;
    //声明一个通讯簿的引用
    ABAddressBookRef addBook =nil;
    //因为在IOS6.0之后和之前的权限申请方式有所差别，这里做个判断
    if ([[UIDevice currentDevice].systemVersion floatValue]>=6.0) {
        //创建通讯簿的引用
        addBook=ABAddressBookCreateWithOptions(NULL, NULL);
        //创建一个出事信号量为0的信号
        dispatch_semaphore_t sema=dispatch_semaphore_create(0);
        //申请访问权限
        ABAddressBookRequestAccessWithCompletion(addBook, ^(bool greanted, CFErrorRef error)        {
            //greanted为YES是表示用户允许，否则为不允许
            if (!greanted) {
                tip=1;
            }else{
                if([[UIDevice currentDevice].systemVersion floatValue] >= 8.0){
                    nav.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false];
                }
                [self presentViewController:nav animated:YES completion:nil];
                [KLHelp hideAllHUDsForView:self.view animated:YES];
            }
            //发送一次信号
            dispatch_semaphore_signal(sema);
        });
        //等待信号触发
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }else{
        //IOS6之前
        addBook =ABAddressBookCreate();
    }
}

#pragma mark - 选择通讯录列表的代理方法
//取消选择
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
    NSString *phoneNO = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);
    
    if ([phoneNO hasPrefix:@"+"]) {
        phoneNO = [phoneNO substringFromIndex:3];
    }
    phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
    
    self.mobileField.text = phoneNO;
    
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person{
    ABPersonViewController *personViewController = [[ABPersonViewController alloc] init];
    personViewController.displayedPerson = person;
    [peoplePicker pushViewController:personViewController animated:YES];
}

#pragma mark - 获取钥匙的费用
-(void)getGroupTotalFeeWithStartDate:(NSString *)startDate endDate:(NSString *)endDate style:(NSString *)style{
    [KLHelp showHUDAddedTo:self.view animated:YES];
    [KLHttpAPI getNewSendKeyTotalfeeWithStartdate:startDate enddate:endDate completionHandler:^(MKNetworkOperation *operation) {
        NSLog(@"获取的价格:%@",operation.responseString);
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        NSDictionary *dic = operation.responseJSON;
        NSLog(@"获取钥匙费用为:%@",dic);
        NSString *isSuccess = [dic objectForKey:@"success"];
        if(isSuccess.integerValue == 1){
            self.totalFee = [dic objectForKey:@"infor"];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"此次操作支付:¥ %@元",self.totalFee]
                                                            message:nil
                                                   cancelButtonItem:[RIButtonItem itemWithLabel:@"取消" action:nil]
                                                   otherButtonItems:[RIButtonItem itemWithLabel:@"确定" action:^{
//                NSString *amount = [[NSUserDefaults standardUserDefaults] objectForKey:@"feeaccount"];
                //bug 账户明明有钱，显示的却是0, 写个死数据
                NSString *amount = @"100";

                if(amount.doubleValue < self.totalFee.doubleValue){
                    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"当前余额不足" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"充值",@"在线支付", nil];
                    [sheet showInView:self.view];
                }else
                    [self sendGroupBrunchWithStartDate:startDate endDate:endDate style:style];
            }], nil];
            [alert show];
        }else{
            [JRToast showWithText:[dic objectForKey:@"msg"]];
        }
    } errorHandler:^(NSString *error) {
        [JRToast showWithText:error];
    }];
}

#pragma mark - 发送钥匙的网络请求
-(void)sendGroupBrunchWithStartDate:(NSString *)startDate endDate:(NSString *)endDate style:(NSString *)style{
    NSString *userAesKey;
    NSString *rsaKey;
    if (style.integerValue == 1){
        userAesKey = [KLHelp getUserSixTeenRandomAESKey];
        rsaKey = [KLHelp getLockRSAPublicKeyWithLockName:[self.lockDetailDic objectForKey:@"uname"]];
        if(rsaKey.length == 0){
            [KLHelp showTextHUDforView:self.view text:@"公钥丢失，请重新扫描二维码！"];
            return ;
        }
        if(self.foreverBrunch.isSelected){
            self.beginTimeToLock = @"000000000000";
            self.endTimeToLock = @"000000000000";
        }
        NSData *packageChildKey = [BuleFuction packChildkeyToData:rsaKey mobileStr:self.mobileField.text startTime:self.beginTimeToLock endTime:self.endTimeToLock commondCode:@"0" userAESKey:userAesKey];
        rsaKey = [packageChildKey convertDataToHexStr:packageChildKey];
    }else{
        rsaKey = @"";
        userAesKey = @"";
    }
    
    [KLHelp showHUDAddedTo:self.view animated:YES];
    [KLHelp showTextHUDforView:self.view text:@"正在分发钥匙..." dismissedOperate:nil];
    [KLHttpAPI distributeChild_keyWithLockID:[self.lockDetailDic objectForKey:@"id"] mobile:self.mobileField.text startdate:startDate enddate:endDate totalfee:self.totalFee rsa_data:rsaKey style:style from_key_id:[self.lockDetailDic objectForKey:@"keyid"] AESkey:userAesKey power:power updatetime:updatetime token:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] commondCode:@"a1" completionHandler:^(MKNetworkOperation *operation) {
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            NSLog(@"发送钥匙返回数据:%@",operation.responseString);
            NSDictionary *dic = operation.responseJSON;
            [KLHelp showTextHUDforView:self.view text:[dic objectForKey:@"msg"]];
        } errorHandler:^(NSString *error) {
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            [KLHelp showTextHUDforView:self.view text:error];
        }];
}

#pragma mark - UIActionSheetDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%zd",buttonIndex);
    if(buttonIndex == 0){//充值
        KLRechargeViewController *rechargeVC = [[KLRechargeViewController alloc]init];
        [self.navigationController pushViewController:rechargeVC animated:YES];
    }else if(buttonIndex == 1){//在线支付
        //设置支付代理
        self.money = [NSString stringWithFormat:@"%.f",self.totalFee.doubleValue * 100];
        [BeeCloud setBeeCloudDelegate:self];
        //充值
        [self recharge];
    }
}

-(void)recharge{
    //本机当前时间(用于自定义单号)
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMddHHmmss"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    
    //支付请求
    [BeeCloud initWithAppID:@"1e70e317-1286-490b-ad3b-3d56f8f2e0a0" andAppSecret:@"caf7da3a-1b60-499c-920c-5d0c2008693a"];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:self.money,[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"], nil];
    /**
     按住键盘上的option键，点击参数名称，可以查看参数说明
     **/
    BCPayReq *payReq = [[BCPayReq alloc] init];
    payReq.channel = PayChannelAliApp; //支付渠道
    payReq.title = @"KISSLOCK蓝牙锁在线支付";//订单标题
    payReq.totalFee = [NSString stringWithFormat:@"%@",self.money];//订单价格
    self.trade_no = [NSString stringWithFormat:@"0002%@%@",locationString,[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"]];
    payReq.billNo = self.trade_no;//商户自定义订单号
    payReq.scheme = @"prefsGuoYangKissLock";//URL Scheme,在Info.plist中配置; 支付宝必有参数
    payReq.billTimeOut = 300;//订单超时时间
    payReq.viewController = self; //银联支付和Sandbox环境必填
    payReq.optional = dict;//商户业务扩展参数，会在webhook回调时返回
    [BeeCloud sendBCReq:payReq];
}

#pragma mark - BCPay回调
- (void)onBeeCloudResp:(BCBaseResp *)resp {
    if(resp.type == BCObjsTypePayResp){
        // 支付请求响应
        BCPayResp *tempResp = (BCPayResp *)resp;
        if (tempResp.resultCode == 0) {
            NSLog(@"支付情况：%@",resp.resultMsg);
            [KLHttpAPI payoffSuccessWithKeytype:@"1" total_fee:self.money trade_no:self.trade_no completionHandler:^(MKNetworkOperation *operation) {
                NSLog(@"充值返回数据：%@",operation.responseString);
                NSDictionary *dic = operation.responseJSON;
                NSString *isSuccess = [dic objectForKey:@"success"];
                if(isSuccess.integerValue == 1){
                    [[NSUserDefaults standardUserDefaults] setObject:[dic objectForKey:@"msg"] forKey:@"feeaccount"];
                    //钥匙的有效期
                    NSString *startDate; NSString *endDate;
                    if(self.foreverBrunch.isSelected){
                        startDate = @"0";
                        endDate = @"0";
                    }else{
                        if(![self.beginTime.titleLabel.text hasPrefix:@"2"] || ![self.endTime.titleLabel.text hasPrefix:@"2"]){
                            [JRToast showWithText:@"请选择钥匙有效期"];
                            return ;
                        }else{
                            startDate = [NSString stringWithFormat:@"%@:00",self.beginTime.titleLabel.text];
                            endDate = [NSString stringWithFormat:@"%@:00",self.endTime.titleLabel.text];
                        }
                    }
                    NSString *style = [self.lockDetailDic objectForKey:@"type"];
                    [self sendGroupBrunchWithStartDate:startDate endDate:endDate style:style];
                }else{
                    [KLHelp showTextHUDforView:self.view text:@"充值失败"];
                }
            } errorHandler:^(NSString *error) {
                [KLHelp showTextHUDforView:self.view text:@"充值失败"];
            }];
        } else {
            //支付取消或者支付失败
            NSLog(@"支付取消或失败结果信息:resultMsg：%@, errDetail：%@, type：%zd, resultCode：%zd",tempResp.resultMsg,tempResp.errDetail,tempResp.request.type,tempResp.resultCode);
        }
    }
}

#pragma mark - 滑动取消键盘
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.mobileField endEditing:YES];
}

@end
